package com.wuming.house.security;


import com.wuming.house.model.Member;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;

/**********************************************************
 * 权限工具类
 *
 * @author zhangyu
 * @date 2016-4-24
 * @time 上午12:13:03
 **********************************************************/
public class SecurityHander {

    public static String CURENTUSER = "CURENTSECURETITYUSER";

    public static String CURRENT_WX_USER = "CURRENTWXUSER";

    public static Integer getCurrentUserId() {
        Member user = SecurityHander.getCurrentUser();
        if (null != user) {
            return user.getId();
        } else {
            return null;
        }
    }


    public static String getCurrentUserName() {
        Member user = SecurityHander.getCurrentUser();
        if (null != user) {
            return user.getUserName();
        } else {
            return null;
        }
    }

    public static Member getCurrentUser() {
        Subject currentUser = SecurityUtils.getSubject();
        Member result = null;
        if (null != currentUser) {
            Session session = currentUser.getSession();
            if (null != session) {
                Object u = session.getAttribute(SecurityHander.CURENTUSER);
                if (null != u) {
                    return (Member) u;
                }
            }
        }
        return result;
    }


    /**
     * 将一些数据放到ShiroSession中,以便于其它地方使用
     *
     * @see 比如Controller,使用时直接用HttpSession.getAttribute(key)就可以取到
     */
    public static void setSession(Object key, Object value) {
        Subject currentUser = SecurityUtils.getSubject();
        if (null != currentUser) {
            Session session = currentUser.getSession();
            if (null != session) {
                session.setAttribute(key, value);
            }
        }
    }

    public static Object getFromSession(Object key) {
        Subject currentUser = SecurityUtils.getSubject();
        Object result = null;
        if (null != currentUser) {
            Session session = currentUser.getSession();
            if (null != session) {
                Object u = session.getAttribute(key);
                if (null != u) {
                    return u;
                }
            }
        }
        return result;
    }

}
